package com.bigshen.algorithm.gTree.solution03InorderTraversal;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Solution {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        public TreeNode(int val) {
            this.val = val;
        }
    }

    public List<Integer> inorderTraversal(TreeNode root) {

        List<Integer> list = new ArrayList<>();

        if (null == root) {
            return list;
        }

        // 递归实现
        //inorder(root, list);

        // 栈实现
        Stack<TreeNode> stack = new Stack();
        TreeNode node = root;
        while (null != node || !stack.isEmpty()) {
            while (null != node) {
                stack.push(node);
                node = node.left;
            }
            node = stack.pop();
            list.add(node.val);
            node = node.right;
        }

        return list;

    }

    // 递归实现
    private void inorder(TreeNode node, List<Integer> list) {

        if (null == node) {
            return;
        }
        inorder(node.left, list);
        list.add(node.val);
        inorder(node.right, list);

    }


}
